package com.service;

import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.bean.SysFunctionBean;
import com.common.GlobalPara;
import com.common.exception.AppException;
import com.common.utils.MD5Util;
import com.dao.LoginDao;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.model.Function;
import com.model.User;

public class LoginService {
	public static final LoginService service = new LoginService();

	private List<Function> getFunctionsByUser(User u) {
		String userid= u.getUserid();
		User user = User.dao.findById(userid);
		if (user == null) {
			throw new AppException("用户id " + userid + " 不存在！");
		}
		List<Function> functionList = new ArrayList<Function>();
		//管理员admin获取全部的权限
		if(!u.getLoginId().equals("admin")){
			//支持到二级菜单
			StringBuffer sqlBF = new StringBuffer();
			sqlBF.append("  SELECT                               ");
			sqlBF.append("  	c.functionid ,c.parentid,d.parentid  pparentid        ");
			sqlBF.append("  FROM                                 ");
			sqlBF.append("  	role_function a                 ");
			sqlBF.append("  	left join FUNCTION c                       ");
			sqlBF.append("  on a.functionid = c.functionid      ");
			sqlBF.append("      left join FUNCTION d ");
			sqlBF.append("  on c.parentid =d.functionid ");
			sqlBF.append("  WHERE                                ");
			sqlBF.append("  	a.roleid IN (                    ");
			sqlBF.append("  		SELECT                       ");
			sqlBF.append("  			b.roleid                  ");
			sqlBF.append("  		FROM                         ");
			sqlBF.append("  			user b              ");
			sqlBF.append("  		WHERE                        ");
			sqlBF.append("  			b.userid =?              ");
			sqlBF.append("  	)                                ");
			sqlBF.append("");
			functionList = Function.dao.find(sqlBF.toString(),userid);
			StringBuffer funcStringBF = new StringBuffer();
			for(Function func:functionList){
				if(!StrKit.isBlank(func.getFunctionid())){
					funcStringBF.append("'"+func.getFunctionid()+"',");
				}
				if(!StrKit.isBlank(func.getParentid())){
					funcStringBF.append("'" + func.getParentid()+"',");
				}
				if(!StrKit.isBlank(func.getStr("pparentid"))){
					funcStringBF.append("'" + func.getStr("pparentid")+"',");
				}
			}
			//查询出一级菜单和二级菜单以及按钮
			if(funcStringBF.length()!=0){
				String funcStr = funcStringBF.toString();
				funcStr = "(" + funcStr.substring(0, funcStr.length()-1) + ")";
				functionList = Function.dao.find("SELECT * from function where functionid in " + funcStr + " and parentid is not null ORDER BY sx ");
			}
		}else{
			functionList = Function.dao.find("select * from function where parentid is not null Order by sx ");
		}
		
		return functionList;
	}
	public Function getRootFunction(){
		List<Function> rootFuncList = Function.dao.find("SELECT * from function where parentid is null");
		if(rootFuncList.size()>0){
			return rootFuncList.get(0);
		}else{
			return null;
		}
	}

	public Ret getPermission(User user) {
		Ret result = new Ret();
		List<Function> functionList = this.getFunctionsByUser(user);
		Map<String, String> buttonPerMap = new HashMap<String, String>();
		if(functionList == null || functionList.size()==0){
			throw new AppException("该用户无该系统的功能权限！");
		}
		
		Function rootfuc = this.getRootFunction();
		if(rootfuc == null){
			throw new AppException("菜单配置错误，根菜单不存在！");
		}
		
		List<SysFunctionBean> levelOneFuncList = new ArrayList<SysFunctionBean>();
		

		SysFunctionBean temp;
		for (Function function : functionList) {
			//获取跟菜单和功能按钮集合
			if (function.getGnlx().equals(GlobalPara.GNLX_BUTTON)) {// 按钮
				buttonPerMap.put(function.getFunctionid(), "");
			//获取一级菜单
			}else if(function.getParentid()!=null && function.getParentid().equals(rootfuc.getFunctionid())){
				temp = new SysFunctionBean();
				temp.setSelf(function);
				levelOneFuncList.add(temp);
			}
		}
		
		//获取一级菜单的子菜单
		for(SysFunctionBean function:levelOneFuncList){
			for (Function fun : functionList) {
				if(fun.getParentid()!=null && fun.getParentid().equals(function.getSelf().getFunctionid())){
					function.getChildren().add(fun);
				}
			}
		}

		result.set(GlobalPara.BUTTON_PERMAP,buttonPerMap);
		result.set("menudata",levelOneFuncList);
		return result;
	}
	public User valiLogin(String username ,String password) throws NoSuchAlgorithmException{
		if(StrKit.isBlank(username)){
			throw new AppException("用户名为空");
		}
		if(StrKit.isBlank(password)){
			throw new AppException("密码为空！");
		}
		
		User user = LoginDao.dao.getUserByLoginId(username);
		if(user == null){
			throw new AppException("用户不存在！");
		}
		
		String passwordDB = user.getPassword();
		if(!passwordDB.equals(MD5Util.toMd5Str(password))){
			throw new AppException("密码不正确");
		}
		
		return user;
	}
}
